// 行为交收模态框
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { InputNumberC, TableC, ModalC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import accounting from 'accounting';
@Form.create()
 class SettlementModalC extends PureComponent {
  // props默认值
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
  };
  state = {
    columns: [], // 表格列
    dataSource: [], // 表格数据
    isEdit: false, // 表格状态
  };

  //初始化函数
  componentDidMount() {
    this.props.onRef(this);
    this.getTableData();
  }

  //获取信息表格数据
  getTableData = () => {
    this.setState({
      // 表格loading
      columns: undefined,
      dataSource: undefined,
    });
    this.props.dispatch({
      type: 'moreFundsOrderM/getSettlementModalData',
      payload: {
        id: this.props.tradeInfo.id,
      },
      callback: (data) => {
        if (data) {
          this.columnsChange(data.columns);
          this.setState({
            dataSource: data.dataSource,
          });
        } else {
          this.setState({
            columns: [],
            dataSource: [],
          });
        }
      },
    });
  };

  // 表格数据列优化
  columnsChange = (columns) => {
    columns.forEach((item) => {
      if (item.key == 'settlementAmount') {
        item.render = (val, record) => {
          if (record.edit) {
            return (
              <InputNumberC form={this.props.form} dataIndex={'settlementAmount'} initialValue={val ? val : ''} precision={4} min={0} rules={[{ required: true, message: ' ' }]} />
            );
          } else {
            if (val == null || val === undefined || val === '') {
              return '--';
            } else {
              // NaN: Not a Number
              // isNaN()的缺点就在于 null、空格以及空串会被按照0来处理
              if (isNaN(val)) {
                return val;
              } else {
                return accounting.formatNumber(Number(val), 4);
              }
            }
          }
        };
      }
    });
    if (columns.length && columns[columns.length - 1].title != '操作') {
      // 处理不同类型的交易方向禁用编辑逻辑
      let rules = [];
      switch (this.props.type) {
        case '0':
          if (this.props.tradeInfo.direction == '6') {
            //债券交易方向为付息时允许编辑为其他时不允许编辑
            rules = [
              { key: 'isDisabled', value: [undefined], relation: ['!='] },
              { key: 'isSettlement', value: ['4', '7', '8'], relation: ['=', '=', '='] },
            ];
          } else {
            rules = [{ key: 'disabled', value: [undefined], relation: ['='] }];
          }
          break;
        case '4':
          rules = [
            { key: 'isDisabled', value: [undefined], relation: ['!='] },
            { key: 'isSettlement', value: ['4', '7', '8'], relation: ['=', '=', '='] },
          ]; //回购禁用逻辑
          break;

        case '7':
          if (this.props.tradeInfo.direction == '6' || this.props.tradeInfo.direction == '7') {
            //理财直融交易方向为付息和到期时允许编辑为其他时不允许编辑
            rules = [
              { key: 'isDisabled', value: [undefined], relation: ['!='] },
              { key: 'isSettlement', value: ['4', '7', '8'], relation: ['=', '=', '='] },
            ];
          } else {
            rules = [{ key: 'disabled', value: [undefined], relation: ['='] }];
          }
          break;

        case '12':
          if (this.props.tradeInfo.direction == '6' || this.props.tradeInfo.direction == '7') {
            //非标交易方向为付息和到期时允许编辑为其他时不允许编辑
            rules = [
              { key: 'isDisabled', value: [undefined], relation: ['!='] },
              { key: 'isSettlement', value: ['4', '7', '8'], relation: ['=', '=', '='] },
            ];
          } else {
            rules = [{ key: 'disabled', value: [undefined], relation: ['='] }];
          }
      }
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.editData(record);
            },
            rules: {
              // 禁用逻辑：某条数据处于编辑状态或当前数据已交收
              disabled: {
                items: rules,
                relation: 'or',
              },
              // 隐藏逻辑：点击编辑时隐藏编辑和删除按钮，展示保存和取消按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['!='] }] },
            },
          },
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveData(record);
            },
            rules: {
              // 隐藏逻辑：点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['='] }] },
            },
          },
          {
            title: '取消',
            onClick: (record, index) => {
              this.cancelData(record);
            },
            rules: {
              // 隐藏逻辑：点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['='] }] },
            },
          },
        ],
      });
    }
    this.setState({ columns: columns });
  };

  //响应编辑
  editData = (record) => {
    const { dataSource } = this.state;
    this.setState({
      isEdit: true, // 表格处于编辑状态
      editDataSource: record,
    });
    var lists = dataSource.concat();
    lists.map((item) => {
      item.isDisabled = true;
      if (item.id == record.id) {
        item.edit = true;
      }
    });
    this.saveDataSource(lists)
    
  };
  //保存dataSource 更新视图 否则数据更新 视图不更新
  saveDataSource=(dava)=>{
    this.setState({
      dataSource:JSON.parse(JSON.stringify(dava))
    })
  }

  // 保存响应
  saveData = (record) => {
    const {
      form: { validateFields },
    } = this.props;
    validateFields((err, fieldsValue) => {
      if (!err) {
        this.setState({
          isEdit: false, // 解除表格编辑状态
        });
        this.state.dataSource.map((item) => {
          item.isDisabled = undefined;
          if (item.id == record.id) {
            item.edit = undefined;
            item.settlementAmount = this.props.form.getFieldValue('settlementAmount');
          }
        });
        this.saveDataSource(this.state.dataSource)
      } else {
        message.error('请填写结算金额');
      }
    });
  };

  // 取消响应
  cancelData = (record) => {
    this.setState({
      isEdit: false, // 解除表格编辑状态
    });
    this.state.dataSource.map((item) => {
      item.isDisabled = undefined;
      if (item.id == record.id) {
        item.edit = undefined;
        item = this.state.editDataSource;
      }
    });
    this.saveDataSource(this.state.dataSource)
  };

  // 确定响应
  onOk = () => {
    if (this.state.isEdit) {
      message.warning('请先保存编辑的数据');
      return;
    }
    this.props.dispatch({
      type: 'moreFundsOrderM/settlementModalBehaviorData',
      payload: {
        id: this.props.tradeInfo.id,
        data: this.state.dataSource,
      },
      callback: (flg) => {
        if (flg) {
          this.props.onOk();
        }
      },
    });
  };

  render() {
    const { columns, dataSource } = this.state;
    return (
      <ModalC
        title={'交收'}
        visible={this.props.visible}
        maskClosable={false}
        footer={undefined}
        width={800}
        onOk={this.onOk}
        onCancel={() => this.props.onCancel()}
        confirmLoading={this.props.loading.effects['moreFundsOrderM/settlementModalData'] === true}
      >
        <TableC columns={columns} dataSource={dataSource} scroll={{ y: window.innerHeight - 500 < 100 ? 100 : window.innerHeight - 500 }} rowKey='id' hidePage={true} />
      </ModalC>
    );
  }
}

export default connect(({ moreFundsOrderM, loading }) => ({ moreFundsOrderM, loading }))(SettlementModalC);
